package com.wx.spider.mobile.socket;

import com.wx.spider.common.model.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author:feng
 * @create:2021-04-22 20:41
 */
@Slf4j
@ServerEndpoint(value = "/socket/appmsg")
@Component
public class AppmsgWebSocket {

    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /** 存放所有在线的客户端 */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static String getParamFromSessoion(Session session, String name){
        List<String> paramList = session.getRequestParameterMap().get(name);
        if(paramList != null && paramList.size() > 0){
            return paramList.get(0);
        }else {
            return null;
        }
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet(); // 在线数加1
        clients.put(session.getId(), session);

        log.info("有新模拟器连接加入：{}，当前在线终端数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(session.getId());
        log.info("有一模拟器连接关闭：{}，当前在线终端数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("模拟器服务端收到客户端[{}]的消息:{}", session.getId(), message);
        this.sendMessage(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("模拟器发生错误");
        error.printStackTrace();
    }

    /**
     * 群发消息不包含自己
     *
     * @param message
     *            消息内容
     */
    private void sendMessage(String message, Session fromSession) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            // 排除掉自己
            if (!fromSession.getId().equals(toSession.getId())) {
                log.info("模拟器服务端给客户端[{}]发送消息{}", toSession.getId(), message);
                toSession.getAsyncRemote().sendText(message);
            }
        }
    }
    /**
     * 群发消息所有
     *
     * @param message
     *            消息内容
     */
    public void sendMessage(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            log.info("模拟器服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getAsyncRemote().sendText(message);
        }
    }

    /**
     * 群发消息所给空闲手机号
     *
     * @param message
     *            消息内容
     */
    public void sendMessageToFree(String message) {

        List<String> phoneList = stringRedisTemplate.opsForList().range(Constants.WX_BIZ_GET_APPMSG_PHONE_QUNUE, 0, -1);

        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            String phone = getParamFromSessoion(toSession, "phone");

            if(!phoneList.contains(phone)){
                log.info("模拟器服务端给客户端[{}]发送消息{}", toSession.getId(), message);
                toSession.getAsyncRemote().sendText(message);
            }else{
                log.info("账号[{}]正在运行中", phone);
            }


        }
    }


}
